/**
 * tzw 2017年8月29日14:32:23
 */
/*global module require */
/*eslint no-console: "off" */
// 严格模式
'use strict'

// 引入配置文件（系统基础配置）
const config = require('../config/app.config')

const util = require('util')
// 类似fs，只不过是在内存中的'文件系统'
const { createFsFromVolume, Volume } = require('memfs')
const path = require('path')
const opener = require('opener')
const memory_fs = createFsFromVolume(new Volume())
memory_fs.join = path.join.bind(path)

// Koa框架
const Koa = require('koa')

// Koa实例化出来一个application
const app = new Koa()

const webpack = require('webpack')
const webpack_dev_koa_middleware = require('./middleware/webpackDevKoaMiddleware')
const webpack_hot_koa_middleware = require('./middleware/webpackHotKoaMiddleware')
// const { devMiddleware, hotMiddleware } = require('koa-webpack-middleware')

// const compress = require('koa-compress')

const Env = require('./node_app_render/nunjucksEnv')

const html = Env.render('index.html', {
  script_tags:
    '<script src="/vendor.js"></script><script src="/app.js"></script>'
})


// 打包前端代码
const webpack_client_config = require(`${config.CONFIG_ROOT}/webpack.config.js`)
const client_compiler = webpack(webpack_client_config[1])

const webpack_dev_instance = webpack_dev_koa_middleware(client_compiler, {
  outputFileSystem: memory_fs,
  publicPath: webpack_client_config[1].output.publicPath
})

// 内存部署
app.use(webpack_dev_instance)
app.use(webpack_hot_koa_middleware(client_compiler))

app.use(async (ctx, next) => {
  console.log(`请求网址：${ctx.request.url}`)

  ctx.response.type = 'html'
  ctx.response.body = html
  await next()
})

webpack_dev_instance.waitUntilValid(() => {
    memory_fs.writeFileSync(
      path.join(webpack_client_config[1].output.publicPath, config.HTML_NAME),
      html
    )

    // 监听端口
    app.listen(config.PORT, () => {
      console.log(`正在监听端口：${config.PORT}`)
      opener(`http://127.0.0.1:${config.PORT}`)
    })
})
